package org.soenea.doitall.domain.model.invite.data;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.dsrg.soenea.service.logging.SQLLogger;
import org.dsrg.soenea.service.threadLocal.DbRegistry;

public class InviteTDG {
	public static final String BASE_NAME = "invite";
	public static final String TABLE = DbRegistry.getTablePrefix()+BASE_NAME;

	public static final String INSERT = "INSERT INTO " + TABLE + "(inviteID, userIdInviter, userIdInvited, groupID, version, status) VALUES(?, ?, ?, ?, 1, 0);";
	public static final String UPDATE = "UPDATE " + TABLE + " AS p set p.status=?, p.version=p.version+1 WHERE p.inviteID=?  AND p.version=?;";
	
	public final static String CREATE_TABLE = 
			"CREATE TABLE IF NOT EXISTS " + TABLE + " (" +
			"inviteID BIGINT,"+
			"userIdInviter BIGINT,"+
			"userIdInvited BIGINT,"+
			"groupID BIGINT,"+
			"version INT,"+
			"status INT,"+
			"PRIMARY KEY(inviteID)"+
			") ENGINE=InnoDB;";
			  
	public final static String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE + ";";

	public static void createTable() throws SQLException {
		SQLLogger.processUpdate(DbRegistry.getDbConnection().createStatement(), CREATE_TABLE);
	}
	
	public static void dropTable() throws SQLException {
		SQLLogger.processUpdate(DbRegistry.getDbConnection().createStatement(), DROP_TABLE);
	}
	
	public static int  update(long inviteID, int Status, long version) throws SQLException {
		PreparedStatement ps = DbRegistry.getDbConnection().prepareStatement(UPDATE);
		ps.setInt(1, Status);
		ps.setLong(2, inviteID);
		ps.setLong(3, version);		
		int count = ps.executeUpdate();
		ps.close();
		return count;
	}
	
	public static void insert(long inviteID, long userIdInviter, long userIdInvited, long groupID) throws SQLException {
		PreparedStatement ps = DbRegistry.getDbConnection().prepareStatement(INSERT);
		ps.setLong(1, inviteID);
		ps.setLong(2, userIdInviter);
		ps.setLong(3, userIdInvited);
		ps.setLong(4, groupID);
		ps.execute();
		ps.close();
	}
}
